import psutil
import os

def set_cpu_affinity_for_non_system_processes(exclude_cores=1):
    # 获取系统中所有 CPU 核心数量
    total_cores = psutil.cpu_count(logical=False)
    if total_cores <= exclude_cores:
        print("CPU 核心数量不足以排除指定的核心数。")
        return

    # 获取所有非系统进程
    for proc in psutil.process_iter(['pid', 'name', 'username']):
        try:
            # 排除系统进程和当前 Python 进程
            if proc.info['username'] == 'SYSTEM' or proc.info['pid'] == os.getpid():
                continue

            # 获取当前进程的 CPU 亲和性
            current_affinity = proc.cpu_affinity()
            print(f"进程 {proc.info['name']} (PID: {proc.info['pid']}) 当前的 CPU 亲和性: {current_affinity}")

            # 设置新的 CPU 亲和性（排除一个核心）
            new_affinity = list(range(1, total_cores))  # 排除核心 0
            # 获取所有核心的列表
            all_cores = list(range(total_cores))  # 从 0 到 total_cores - 1   
            proc.cpu_affinity(all_cores)
            #proc.cpu_affinity(new_affinity)
            print(f"进程 {proc.info['name']} (PID: {proc.info['pid']}) 新的 CPU 亲和性: {new_affinity}")

        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as e:
            pass

if __name__ == "__main__":
    set_cpu_affinity_for_non_system_processes()